package org.achao.redis;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * 订阅 Redis 的消息通道（Channel）并注册一个或多个消息监听器，当消息到达订阅的通道时，会触发监听器的逻辑。
 */
@Configuration
@EnableCaching
public class RedisMsgListenerContainer {

    public static final String PRIVATE_MSG = "redis::private::msg";
    public static final String PUBLIC_MSG = "redis::public::msg";


    /**
     * redis的发布与订阅(监听)
     *
     * @param factory
     * @param listener
     * @return
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory,
                                                   RedisMessageListener listener)
    {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        //订阅频道  这个container 可以添加多个 messageListener
        container.addMessageListener(listener, new ChannelTopic(PUBLIC_MSG));
        container.addMessageListener(listener, new ChannelTopic(PRIVATE_MSG));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(RedisMessageListener receiver) {
        // 消息监听适配器
        return new MessageListenerAdapter(receiver, "onMessage");
    }

}
